from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from drf_haystack.viewsets import HaystackViewSet
from rest_framework import mixins, status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, GenericViewSet

from articles.models import Article, Channel, Comment
from articles.serializers.article import ChannelSerializers, ArticleChannelViewSerializers, UploadArticleSerializers, \
    CommentArticleSerializer, DetailedArticleViewSerializers,ArticleHaystackSerializer
from articles.utils import ArticlePageNumberPagination, SearchArticlePageNumberPagination


class GetChannelsView(ListAPIView):
    '''频道列表视图'''

    serializer_class = ChannelSerializers

    queryset = Channel.objects.all()

    pagination_class = ArticlePageNumberPagination


class ArticleChannelView(mixins.ListModelMixin,GenericViewSet):
    '''文章列表视图'''
    serializer_class = ArticleChannelViewSerializers
    queryset = Article.objects.all()
    @action(methods=['get'],detail=True)
    def channel(self,request,pk):
        '''get请求'''

        if pk == "-1":

           queryset = Article.objects.all()

        else:

            channel = Channel.objects.get(id=pk)

            queryset = channel.articles.all()

        page = self.paginate_queryset(queryset)

        if page is not None:

            serializer = self.get_serializer(page, many=True)
                # 查看数据是否存在

            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        return Response(serializer.data)

    lookup_value_regex = '-1|\d+'

    pagination_class = ArticlePageNumberPagination


class DetailedArticleView(mixins.RetrieveModelMixin,GenericViewSet):
    '''文章详情视图'''
    serializer_class = DetailedArticleViewSerializers

    queryset = Article.objects.all()



class CollectArticleView(ModelViewSet):
    '''收藏、取消收藏文章视图'''

    permission_classes = [IsAuthenticated]

    serializer_class = UploadArticleSerializers

    def create(self, request, *args, **kwargs):
        '''添加文章'''
        data = request.data
        data['user'] = request.user.id
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    @action(methods=['put'],detail=True)
    def collect(self,request,pk):
        '''get请求'''
        '''收藏、取消收藏'''
        username = request.user.username
        article = Article.objects.get(id=pk)
        # 将这句话提到前面最开始的位置:
        redis_conn = get_redis_connection('article')
        # 进入函数后, 先获取存储在 redis 中的数据
        send_flag = redis_conn.hget('article_flag_%s' % username,article.id)
        # 查看数据是否存在
        if send_flag:

            redis_conn.hdel('article_flag_%s' % username,article.id)

            article.collected_users.remove(request.user.id)

            data = {"message": "ok", "success": True}

        else:
            # 保存点赞信息
            redis_conn.hset('article_flag_%s' % username,article.id, 'True')

            article.collected_users.add(request.user.id)

            article.save()

            data = {"message": "ok", "success": True}

        return Response(data, status=status.HTTP_201_CREATED)

    lookup_value_regex = '\d+'


    @action(methods=['post'],detail=True)
    def publish_comment(self, request,pk):
        '''评论⽂文章'''
        parent = request.data.get('parent')

        content = request.data.get('content')

        if parent:

            try:

                Comment.objects.filter(article=pk).create(user_id=request.user.id,article_id=pk,content=content,parent_id=parent)

            except Exception:

                return Response({"message": "failed", "success":False},status=status.HTTP_404_NOT_FOUND)

            return Response({"message": "ok", "success": True},status=status.HTTP_201_CREATED)

        else:

            data = request.data

            data['id'] = pk

            data['user'] = request.user.id

            serializers = CommentArticleSerializer(data = data)
            serializers.is_valid(raise_exception=True)
            serializers.save()
            return Response({"message": "ok", "success": True},status=status.HTTP_201_CREATED)


class ArticleSearchViewSet(HaystackViewSet):
    '''文章搜索接口视图'''

    index_models = [Article]

    serializer_class = ArticleHaystackSerializer

    pagination_class = SearchArticlePageNumberPagination

    ookup_value_regex = '\d+'

